import { config } from '../config.js'

const tips = {
  1: '报错，出现了一个错误',
  1005: '不正确的开发者key',
  200: '你已经点过赞了',
  2001: '你还没点过赞',
  3000: '不正确的开发者key'
}

class HTTP {
  request ({url, data = {}, method = 'GET'}) {
    return new Promise((resolve, reject) => {
      this._request(url, resolve, reject, data, method)
    })
  }
  
  _request (url, resolve, reject, data = {}, method = 'GET') {
    const { api_base_url, appkey } = config

    wx.request({
      url: api_base_url + url,
      method,
      data,
      header: {
        'content-type': 'application/json',
        appkey
      },
      success: (res) => {
        const { statusCode, data } = res
        const { error_code } = data

        if (statusCode.toString().startsWith('2')) {
          resolve(data)
        } else {
          this._showError(error_code)
          reject()
        }
      },
      fail: (err) => {
        this._showError(1)
        reject()
      }
    })
  }

  _showError (errorCode) {
    if (!errorCode) {
      errorCode = 1
    }
    wx.showToast({
      title: tips[errorCode] || tips[1],
      icon: 'none',
      duration: 3000
    })
  }
}

export { HTTP }
